import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Spin, Card, Button, Row, Col, message, Form} from 'antd';
import {validateFeedback} from './utils';
import TextInput from 'Shared/components/TextInput';
import {PAGE, FORM_OPTIONS} from '../constants';
import routes from './routes';
import {feedbackInfo} from './api';
import styles from './style.css';
const FormItem = Form.Item;
export class Feedback extends React.PureComponent {
    state = {
        loading: false,
        validate: false,
        data: {}
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleAbandonClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    handleSubmitClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    handleCloseClick = id => {
        this.setState({
            loading: true
        });
        this.props.onClickClose(id).then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    handleSolvedClick = id => {
        this.setState({
            loading: true
        });
        this.props.onClickSolved(id).then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    openLoding = () => {
        this.setState({loading: true});
    }
    closeLoding = () => {
        this.setState({loading: false});
    }
    handleFilterChange = (value, name) => {
        const {data} = this.state;
        this.setState({
            data: {
                ...data,
                [name]: value,
            },
            hasOperat: true
        });
    };
    onSubmit = () => {
        const {rowVersion} = this.props.detail;
        const {data} = this.state;
        const result = validateFeedback(data);
        if(result) {
            this.setState({
                validate: true,
            });
            return message.warn(result);
        }
        feedbackInfo(this.props.id, {
            analysisResults: data.analysisResults,
            dealMethod: data.dealMethod,
            rowVersion,
        })
            .then(res => {
                if(res.ok)
                    this.props.successReturn();
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    render() {
        const {formatMessage} = this.props.intl;
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            className={styles.marginBottom}
                            title={this.props.intl.formatMessage({
                                id: 'feedback.card.title',
                                defaultMessage: '基本信息'
                            })}>
                            <Row>
                                {
                                    this.props.dealerType === 1 && <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'feedback.form.dealerId',
                                                defaultMessage: '服务站'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            {`${this.props.enterprise.dealerCode}(${this.props.enterprise.dealerName})`}
                                        </FormItem>
                                    </Col>
                                }
                                {
                                    this.props.dealerType === 2 && <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'feedback.form.subDealerId',
                                                defaultMessage: '二级服务站'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            {`${this.props.enterprise.subDealerCode}(${this.props.enterprise.subDealerName})`}
                                        </FormItem>
                                    </Col>
                                }
                            </Row>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'feedback.form.analysisResults',
                                            defaultMessage: '分析结果'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.validate && !this.state.data.analysisResults ? 'error' : null}
                                        required>
                                        <TextInput
                                            name="analysisResults"
                                            value={this.state.data.analysisResults}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'feedback.form.dealMethod',
                                            defaultMessage: '处理方式'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.validate && !this.state.data.dealMethod ? 'error' : null}
                                        required>
                                        <TextInput
                                            name="dealMethod"
                                            value={this.state.data.dealMethod}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card>
                            <Row>
                                <Col className="col-align-right">
                                    <Button key="submit"
                                        onClick={this.onSubmit}
                                        type="primary"
                                        loading={this.state.loading}>
                                        {formatMessage({
                                            id: 'feedback.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                    
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" disabled={this.props.loading} onClick={this.props.onCancel}>
                        {this.props.intl.formatMessage({
                            id: 'feedback.btn.retrun',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>
            </div>
        );
    }
}
Feedback.propTypes = {
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    isDealerUser: PropTypes.bool.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onClickClose: PropTypes.func.isRequired,
    onClickSolved: PropTypes.func.isRequired,
    onClickSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    dealerType: PropTypes.number,
    enterprise: PropTypes.object,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {getDetail, clearData, onClickAbandonForDetail, tableSearch, onClickSubmitForDetail, onClickClose, onClickSolved} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    enterprise: state.getIn(['page', 'domainData', 'initData', 'enterprise']),
    dealerType: state.getIn(['page', 'domainData', 'initData', 'dealerType']),
    detail: getDetailData(state),
    permissions: getPermissions(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    successReturn: () => {
        dispatch(tableSearch());
        ownProps.history.push(routes.query.url());
    },
    onClickAbandon: () =>
        dispatch(onClickAbandonForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }

            return res.ok;
        }),
    onClickSubmit: id =>
        dispatch(onClickSubmitForDetail(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickClose: id =>
        dispatch(onClickClose(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickSolved: id =>
        dispatch(onClickSolved(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Feedback));
